package top.catblog.security.securityspringmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.catblog.security.securityspringmvc.model.AuthenticationRequest;
import top.catblog.security.securityspringmvc.model.UserDto;
import top.catblog.security.securityspringmvc.service.AuthenticationService;

import javax.servlet.http.HttpSession;

/**
 * @Author 毕晓杰602105
 * @Date 2021/3/14 17:08
 * @Version 1.0
 */
@RestController
public class LoginController {

    @Autowired
    AuthenticationService authenticationService;
    @RequestMapping(value = "/login",produces = {"text/plain;charset=utf-8"})
    public String login(@RequestBody AuthenticationRequest authenticationRequest, HttpSession session){
        UserDto user = authenticationService.authentication(authenticationRequest);
        // 存入SESSION
        session.setAttribute(UserDto.SESSION_USER_KEY,user);
        return user.getUsername()+"登录成功";
    }

    @GetMapping(value = "r/r1",produces = {"text/plain;charset=utf-8"})
    public String r1(HttpSession httpSession){
        String fullname = null;
        Object attribute = httpSession.getAttribute(UserDto.SESSION_USER_KEY);
        if (attribute == null) {
            return "匿名";
        }else {
            UserDto userDto = (UserDto) attribute;
            fullname = userDto.getFullname();
        }
        return fullname+"访问资源r1";
    }

    @GetMapping(value = "logout",produces = {"text/plain;charset=utf-8"})
    public String logout(HttpSession httpSession){
        httpSession.invalidate();
        return "退出成功";
    }

}
